import 'package:aqua_plunge/controller/UserController.dart';
import 'package:aqua_plunge/medal/medalstore_page.dart';
import 'package:aqua_plunge/mine/block_list_page.dart';
import 'package:aqua_plunge/mine/edit_page.dart';
import 'package:aqua_plunge/mine/follow_list_page.dart';
import 'package:aqua_plunge/mine/setting_page.dart';
import 'package:aqua_plunge/page/shop_page.dart';
import 'package:aqua_plunge/util/view_util.dart';
import 'package:aqua_plunge/widget/custom_avatar.dart';
import 'package:clipboard/clipboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:get/get.dart';
import 'package:underline_indicator/underline_indicator.dart';

import '../constants/colors.dart';
import '../controller/DatabaseListController.dart';
import '../model/Creation.dart';
import '../post/post_detail_page.dart';
import '../widget/BroadCasterItemWidget.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  State<MinePage> createState() => _HomPgaeState();
}

class _HomPgaeState extends State<MinePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  final tabs = ["Creations", "Favorites"];

  final DatabaseController _databaseController = Get.find<DatabaseController>();
  final UserController _userController = Get.find<UserController>();

  get walletlayout => Row(
        children: [
          SizedBox(
            width: 80,
            height: 32,
            child: InkWell(
              onTap: (){
                Get.to(() => const ShopPage());
              },
              child: Stack(
                children: [
                  Image.asset(
                    "images/icon_wallet.png",
                    fit: BoxFit.fill,
                  ),
                  Container(
                      alignment: Alignment.center,
                      padding: const EdgeInsets.only(left: 10),
                      child: Text(
                        _userController.userInformation.availableCoins.toString(),
                        style: const TextStyle(
                            color: AppColors.coinsColor, fontSize: 16),
                      ))
                ],
              ),
            ),
          ),
          Expanded(child: Container()),
          GestureDetector(
              onTap: () {
                Get.to(() => const MedalStorePage());
              },
              child: Image.asset(
                "images/icon_store.png",
                width: 24,
                height: 24,
              )),
          const SizedBox(width: 24),
          GestureDetector(
              onTap: () {
                Get.to(() => const SettingPage());
              },
              child: Image.asset(
                "images/icon_setting.png",
                width: 24,
                height: 24,
              ))
        ],
      );

  get userinfolayout => Container(
        padding: const EdgeInsets.only(top: 34, bottom: 24),
        child: Row(
          children: [
            CustomAvatar(
                width: 42,
                height: 42,
                netPath:_userController.userInformation.avatarUrl??_userController.userInformation.avatar??''),
            Expanded(
                child: Container(
              width: double.infinity,
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(left: 10),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(_userController.userInformation.nickname ?? "",
                        style: const TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.left),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        Text(
                          "ID: ${_userController.userInformation.userId}",
                          style: const TextStyle(
                              fontSize: 14, color: AppColors.grayColor),
                          textAlign: TextAlign.left,
                        ),
                        const SizedBox(width: 5),
                        GestureDetector(
                            onTap: () {
                              FlutterClipboard.copy(
                                      _userController.userInformation.userId ?? "")
                                  .then((value) {
                                ToastUtils.showCenter("success");
                              });
                            },
                            child: Image.asset(
                              "images/icon_copy.png",
                              width: 20,
                              height: 20,
                            ))
                      ],
                    ),
                  )
                ],
              ),
            )),
            GestureDetector(
                onTap: () {
                  Get.to(() => const EditPage());
                },
                child: Image.asset(
                  "images/icon_edit.png",
                  width: 52,
                  height: 16,
                ))
          ],
        ),
      );

  get followerlayout => Row(
        children: [
          Expanded(
              child: Column(
            children: [
              Text(
                _userController.userInformation.followNum.toString(),
                style: const TextStyle(fontSize: 16, color: Colors.white),
              ),
              const SizedBox(
                height: 20,
              ),
              const Text(
                "Followers",
                style: TextStyle(fontSize: 12, color: AppColors.grayColor),
              )
            ],
          )),
          Container(
            color: AppColors.grayColor,
            width: 1,
            height: 20,
          ),
          Expanded(
              child: InkWell(
            onTap: () {
              Get.to(() => const FloolowingPage());
            },
            child: Column(
              children: [
                Text(
                  _userController.followingNum.toString(),
                  style: const TextStyle(fontSize: 16, color: Colors.white),
                ),
                const SizedBox(
                  height: 20,
                ),
                const Text(
                  "Following",
                  style: TextStyle(fontSize: 12, color: AppColors.grayColor),
                )
              ],
            ),
          )),
          Container(
            color: AppColors.grayColor,
            width: 1,
            height: 20,
          ),
          Expanded(
              child: InkWell(
            onTap: () {
              Get.to(() => const BlockListPage());
            },
            child: Column(
              children: [
                Text(
                  _userController.blockNum.toString(),
                  style: const TextStyle(fontSize: 16, color: Colors.white),
                ),
                const SizedBox(
                  height: 20,
                ),
                const Text(
                  "Block",
                  style: TextStyle(fontSize: 12, color: AppColors.grayColor),
                )
              ],
            ),
          )),
        ],
      );

  late TabController _controller;

  get _tabBar => PreferredSize(
        preferredSize: const Size.fromHeight(40),
        child: Align(
          alignment: Alignment.centerLeft,
          child: TabBar(
              isScrollable: true,
              controller: _controller,
              unselectedLabelColor: AppColors.grayColor,
              labelColor: Colors.white,
              labelStyle:
                  const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
              indicatorSize: TabBarIndicatorSize.label,
              indicator: const UnderlineIndicator(
                  strokeCap: StrokeCap.round,
                  borderSide: BorderSide(color: Colors.white, width: 3),
                  insets: EdgeInsets.only(bottom: 15)),
              tabs: tabs.map<Tab>((String value) {
                return Tab(text: value);
              }).toList()),
        ),
      );

  @override
  void initState() {
    super.initState();
    _controller = TabController(length: 2, vsync: this);
    _userController.fetchUserData();
    _databaseController.fetchMineData();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Obx((){
      return  Container(
          padding: EdgeInsets.only(
              top: getDeviceTop(context), left: 24, right: 24),
          decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('images/img_mine_bg.png',),fit: BoxFit.cover
              )
          ),
          child: Column(
            children: [
              walletlayout,
              userinfolayout,
              followerlayout,
              Container(
                padding: const EdgeInsets.only(top: 40),
                child: _tabBar,
              ),
              Flexible(
                  child: TabBarView(
                    controller: _controller,
                    children: [
                      _gridView(_databaseController.mineCreations),
                      _gridView(_databaseController.favoritesCreations)
                    ],
                  ))
            ],
          ));
    });
  }

  _gridView(RxList<Creation> datas) {
    return Obx(() {
      return MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: Padding(
              padding: const EdgeInsets.only(left: 0, right: 0),
              child: MasonryGridView.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 17,
                  mainAxisSpacing: 16,
                  itemCount: datas.length,
                  itemBuilder: (BuildContext context, int index) {
                    Creation creations = datas[index];
                    return GestureDetector(
                      onTap: () async {
                        Get.to(() => PageDetailPage(
                              postid: creations.postId!,
                              userid: creations.userId!,
                            ))?.then((value) {
                          if (value == true) {
                            _databaseController.fetchMineData();
                            _databaseController.fetchFavoriteData();
                          }
                        });
                      },
                      child: BroadCasterItemWidget(
                        creation: creations,
                      ),
                    );
                  })));
    });
  }

  @override
  bool get wantKeepAlive => true;
}
